import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { CommentEntity } from './entities/comment.entity';
import { CreateCommentDto } from './dto/create-comment.dto';
import { PostEntity } from 'src/post/entities/post.entity';

@Injectable()
export class CommentService {
  constructor(
    @InjectRepository(CommentEntity) private repo: Repository<CommentEntity>,
    @InjectRepository(PostEntity) private postRepo: Repository<PostEntity>,
  ) {}

  async create(dto: CreateCommentDto, userId: number) {
    const post = await this.postRepo.findOne({where:{id:dto.postId}});
    if (!post) throw new NotFoundException('帖子不存在');
    const comment = this.repo.create({
      content: dto.content,
      post,
      user: { id: userId } as any,
      replyTo: dto.replyToId ? { id: dto.replyToId } as any : null,
    });
    const saved = await this.repo.save(comment);
    await this.postRepo.increment({ id: dto.postId }, 'commentCount', 1);
    return saved;
  }

  async findByPost(postId: number) {
    return this.repo.find({
      where: { post: { id: postId } },
      relations: ['user', 'replyTo'],
      order: { createdAt: 'ASC' },
    });
  }
}
